package admindao

import (
	_ "github.com/go-sql-driver/mysql"
	"vpn-management-server/logger"
	"vpn-management-server/src/dao"
	"vpn-management-server/src/model/adminmodel"
)

func AddAdmin(admin *adminmodel.Admin) (int64, error) {
	sqlStr := "INSERT INTO admin(name,password,`rank`,signer,timestamp) value(?,?,?,?,?)"
	if result, err := dao.GMysqlDB.Conn.Exec(sqlStr, admin.Name, admin.Password, admin.Rank, admin.Signer, admin.TimeStamp); err != nil {
		return -1, err
	} else {
		id, _ := result.LastInsertId()
		return id, nil
	}
}

func DeleteAdmin(aid int) error {
	sqlStr := "DELETE FROM admin where id = ?"
	if _, err := dao.GMysqlDB.Conn.Exec(sqlStr, aid); err != nil {
		return err
	}
	return nil
}

func GetAllAdmins() []*adminmodel.Admin {
	var admins []*adminmodel.Admin
	sqlStr := "SELECT * FROM admin"
	err := dao.GMysqlDB.Conn.Select(&admins, sqlStr)
	if err != nil {
		logger.Logger.Error(err)
		return nil
	}
	return admins

}

func GetAdminByID(id int) (*adminmodel.Admin, bool) {
	var admin adminmodel.Admin
	sqlStr := "SELECT * FROM admin where id = ?"
	err := dao.GMysqlDB.Conn.Get(&admin, sqlStr, id)
	if err != nil {
		logger.Logger.Error(err)
		return nil, false
	}
	return &admin, true
}

func HasAdminByName(name string) bool {
	var adminUser adminmodel.Admin
	sqlStr := "SELECT * FROM admin where name = ?"
	if err := dao.GMysqlDB.Conn.Get(&adminUser, sqlStr, name); err != nil {
		return false
	}
	return true
}

func HasAdminByID(id int) bool {
	var admin adminmodel.Admin
	sqlStr := "SELECT * FROM admin where id = ?"
	err := dao.GMysqlDB.Conn.Get(&admin, sqlStr, id)
	if err == nil {
		return true
	}
	return false
}

func GetRankByName(name string) int {
	var admin adminmodel.Admin
	sqlStr := "SELECT * FROM admin where name = ?"
	err := dao.GMysqlDB.Conn.Get(&admin, sqlStr, name)
	if err != nil {
		logger.Logger.Error(err)
		return -1
	}
	return admin.Rank
}

func GetAdminByName(name string) (*adminmodel.Admin, bool) {
	var admin adminmodel.Admin
	sqlStr := "SELECT * FROM admin where name = ?"
	err := dao.GMysqlDB.Conn.Get(&admin, sqlStr, name)
	if err != nil {
		logger.Logger.Error(err)
		return nil, false
	}
	return &admin, true
}

func UpdateAdminByName(password string, name string, timestamp string) error {
	sqlStr := "UPDATE admin SET password = ?,timestamp = ? where name = ?"
	if _, err := dao.GMysqlDB.Conn.Exec(sqlStr, password, timestamp, name); err != nil {
		return err
	}
	return nil
}
